import jwt
from rest_framework import exceptions
from rest_framework_jwt.settings import api_settings
from rest_framework.authentication import BaseAuthentication
from xiaochengxu import models


class XiaoChengXuAuthentication(BaseAuthentication):
    def authenticate(self, request):
        '''
        raise  Exception(),不在继续往下执行，直接返回
        return None  本次认证完成，执行下一个认证
        return ('x', 'x')   认证成功，不需要再继续执行其他认证了，继续往后权限，节流，试图函数
        '''
        token = request.data.get('token') or request.query_params.get('token')
        if not token:
            raise exceptions.AuthenticationFailed({'code': 10002, 'msg': 'error', 'error': '登录成功之后查看'})
        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
        try:
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            raise exceptions.AuthenticationFailed({'code': 10003, 'msg': 'error', 'error': 'token已经过期'})
        except jwt.DecodeError:
            raise exceptions.AuthenticationFailed({'code': 10004, 'msg': 'error', 'error': 'token格式错误'})
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed({'code': 10005, 'msg': 'error', 'error': '认证失败'})

        jwt_get_userid_from_payload = api_settings.JWT_PAYLOAD_GET_USER_ID_HANDLER
        uid = jwt_get_userid_from_payload(payload)
        user_obj = models.User.objects.filter(id=uid).first()
        return (user_obj, token)
